import axios from 'axios';
import qs from 'qs';
import { notification } from 'antd';

// 拦截request,设置全局请求为ajax请求
axios.interceptors.request.use((config) => {
  config.headers['X-Requested-With'] = 'XMLHttpRequest';
  return config;
});

let isExpireSession = false;

function isEmptyObject(e) {
  for (let t in e) {
    return !1;
  }
  return !0;
}

const treatParam = function(param) {
  if (!param.url) throw new Error('缺失ajax必要参数url');

  let p = {};

  p.fail = function(err) {
    // 处理404错误
    if (err.response && err.response.status == 404) {
      notification['error']({
        message: '访问页面异常',
        description: '您访问的页面不存在',
      });
      throw err;
    }

    if (err.response && err.response.data) {
      let retData = err.response.data;
      if (isExpireSession) {
        return;
      }
      if (retData.code == 600) {
        isExpireSession = true;
      }

      notification['error']({
        message: retData.msg,
        description: isEmptyObject(retData.data) ? '' : JSON.stringify(retData.data),
      });
    } else {
      notification['error']({
        message: '报文解析异常',
        description: err.message,
      });
    }

    throw err;
  };
  return p;
};

const get = async function(param) {
  let p = treatParam(param);

  try {

    let res = await axios({
      method: 'get',
      url: param.url,
      params: param.data,
    });


    return res.data;
  } catch (e) {
    p.fail(e);
  }
};

const post = async function(param) {
  let p = treatParam(param);
  if (!param.contentType) {
    param.contentType = request.CONTENT_TYPE_FORMDATA;
  }

  let data;
  if (param.contentType == request.CONTENT_TYPE_FORMDATA) {
    data = qs.stringify(param.data);
  } else {
    data = param.data;
  }

  try {
    let res = await axios({
      method: 'post',
      url: param.url,
      data: data,
      headers: { 'Content-Type': param.contentType },
    });

    return res.data;
  } catch (e) {
    p.fail(e);
  }
};

const request = {
  get: get,
  post: post,
  CONTENT_TYPE_FORMDATA: 'application/x-www-form-urlencoded;charset=UTF-8',
  CONTENT_TYPE_JSON: 'application/json;charset=UTF-8',
};

export default request;
